<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900 py-8">
    <div class="max-w-6xl mx-auto px-4">
      <!-- 用户信息卡片 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6">
        <div class="flex items-center gap-6">
          <!-- 头像 -->
          <div class="relative group">
            <UserAvatar 
              :avatar="user?.avatar" 
              :nickname="user?.nickname" 
              size="xl"
              class="ring-2 ring-gray-200 dark:ring-gray-700"
            />
            <!-- 上传按钮覆盖层 -->
            <button
              @click="triggerAvatarUpload"
              :disabled="uploadingAvatar"
              class="absolute inset-0 rounded-full bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity disabled:opacity-100"
              title="更换头像"
            >
              <Icon 
                v-if="!uploadingAvatar"
                name="heroicons:camera" 
                class="w-6 h-6 text-white" 
              />
              <Icon 
                v-else
                name="line-md:loading-loop" 
                class="w-6 h-6 text-white" 
              />
            </button>
            <!-- 隐藏的文件输入 -->
            <input
              ref="avatarInput"
              type="file"
              accept="image/*"
              class="hidden"
              @change="handleAvatarUpload"
            />
          </div>
          <div class="flex-1">
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white mb-1">
              {{ user?.nickname || '未设置昵称' }}
            </h1>
            <p class="text-gray-600 dark:text-gray-400">{{ user?.email }}</p>
          </div>
          <div class="text-right">
            <div class="inline-flex items-center gap-2 px-4 py-2 rounded-full"
                 :class="membershipBadgeClass">
              <Icon :name="membershipIcon" class="w-5 h-5" />
              <span class="font-medium">{{ membershipText }}</span>
            </div>
            <p v-if="user?.subscriptionEndDate" class="text-sm text-gray-500 dark:text-gray-400 mt-2">
              到期时间：{{ formatDate(user.subscriptionEndDate) }}
            </p>
          </div>
        </div>
      </div>

      <!-- 会员状态卡片 -->
      <div 
        v-if="authStore.isPremium"
        class="bg-gradient-to-r from-yellow-400 via-amber-500 to-orange-500 rounded-xl shadow-lg p-6 mb-6 text-white"
      >
        <div class="flex items-center justify-between">
          <div class="flex-1">
            <div class="flex items-center gap-2 mb-2">
              <Icon name="heroicons:star-solid" class="w-6 h-6" />
              <h3 class="text-xl font-bold">
                {{ user?.subscriptionType === 'premium' ? '高级会员' : '基础会员' }}
              </h3>
            </div>
            <p class="text-white/90 text-sm mb-1">
              到期时间：{{ formatDate(user?.subscriptionEndDate) }}
            </p>
            <p class="text-white/80 text-xs">
              剩余 {{ daysRemaining }} 天
            </p>
          </div>
          <NuxtLink 
            to="/pricing" 
            class="px-6 py-3 bg-white text-orange-600 rounded-lg font-medium hover:bg-white/90 transition-colors shadow-md"
          >
            续费 / 升级
          </NuxtLink>
        </div>
      </div>

      <!-- 非会员提示卡片 -->
      <div 
        v-else
        class="bg-gradient-to-r from-blue-50 to-purple-50 dark:from-blue-900/20 dark:to-purple-900/20 border-2 border-blue-200 dark:border-blue-800 rounded-xl p-6 mb-6"
      >
        <div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
          <div class="flex-1">
            <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-3">
              升级会员，解锁更多权益
            </h3>
            <ul class="text-sm text-gray-600 dark:text-gray-400 space-y-2">
              <li class="flex items-center gap-2">
                <Icon name="heroicons:check-circle" class="w-4 h-4 text-green-500 flex-shrink-0" />
                访问会员专属工具
              </li>
              <li class="flex items-center gap-2">
                <Icon name="heroicons:check-circle" class="w-4 h-4 text-green-500 flex-shrink-0" />
                无限收藏数量
              </li>
              <li class="flex items-center gap-2">
                <Icon name="heroicons:check-circle" class="w-4 h-4 text-green-500 flex-shrink-0" />
                专属客服支持
              </li>
            </ul>
          </div>
          <NuxtLink 
            to="/pricing" 
            class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg font-medium hover:from-blue-700 hover:to-purple-700 transition-all shadow-md whitespace-nowrap"
          >
            立即升级
          </NuxtLink>
        </div>
      </div>

      <!-- 标签页 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm">
        <div class="border-b border-gray-200 dark:border-gray-700">
          <nav class="flex gap-8 px-6" aria-label="Tabs">
            <button
              v-for="tab in tabs"
              :key="tab.id"
              @click="activeTab = tab.id"
              :class="[
                'py-4 px-1 border-b-2 font-medium text-sm transition-colors',
                activeTab === tab.id
                  ? 'border-blue-600 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
              ]"
            >
              <div class="flex items-center gap-2">
                <Icon :name="tab.icon" class="w-5 h-5" />
                <span>{{ tab.label }}</span>
              </div>
            </button>
          </nav>
        </div>

        <div class="p-6">
          <!-- 我的订单 -->
          <div v-if="activeTab === 'orders'">
            <div v-if="loadingOrders" class="text-center py-12">
              <Icon name="line-md:loading-loop" class="w-8 h-8 text-blue-600 mx-auto" />
            </div>
            <div v-else-if="orders.length === 0" class="text-center py-12">
              <Icon name="heroicons:shopping-bag" class="w-16 h-16 text-gray-400 mx-auto mb-4" />
              <p class="text-gray-600 dark:text-gray-400">暂无订单</p>
              <NuxtLink to="/pricing" class="btn btn-primary mt-4 inline-block">
                去订阅会员
              </NuxtLink>
            </div>
            <div v-else class="space-y-4">
              <div
                v-for="order in orders"
                :key="order.id"
                class="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:shadow-md transition-shadow"
              >
                <div class="flex items-center justify-between mb-3">
                  <div>
                    <span class="text-sm text-gray-500 dark:text-gray-400">订单号：{{ order.orderNo }}</span>
                  </div>
                  <span
                    class="px-3 py-1 rounded-full text-sm font-medium"
                    :class="getOrderStatusClass(order.status)"
                  >
                    {{ getOrderStatusText(order.status) }}
                  </span>
                </div>
                <div class="grid grid-cols-3 gap-4 mb-3">
                  <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">套餐</p>
                    <p class="font-medium text-gray-900 dark:text-white">{{ order.planName || order.subscriptionType }}</p>
                  </div>
                  <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">金额</p>
                    <p class="font-medium text-gray-900 dark:text-white">¥{{ order.totalPrice }}</p>
                  </div>
                  <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">创建时间</p>
                    <p class="font-medium text-gray-900 dark:text-white">{{ formatDate(order.createdAt) }}</p>
                  </div>
                </div>
                <div v-if="order.status === 'pending'" class="flex gap-2">
                  <button
                    @click="goToPay(order.id)"
                    class="btn btn-primary btn-sm"
                  >
                    继续支付
                  </button>
                  <button
                    @click="cancelOrder(order.id)"
                    class="btn btn-secondary btn-sm"
                  >
                    取消订单
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 我的收藏 -->
          <div v-if="activeTab === 'favorites'">
            <div v-if="loadingFavorites" class="text-center py-12">
              <Icon name="line-md:loading-loop" class="w-8 h-8 text-blue-600 mx-auto" />
            </div>
            <div v-else-if="favorites.length === 0" class="text-center py-12">
              <Icon name="heroicons:heart" class="w-16 h-16 text-gray-400 mx-auto mb-4" />
              <p class="text-gray-600 dark:text-gray-400">暂无收藏</p>
              <NuxtLink to="/tools" class="btn btn-primary mt-4 inline-block">
                去发现工具
              </NuxtLink>
            </div>
            <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              <ToolCard
                v-for="favorite in favorites"
                :key="favorite.id"
                :tool="favorite.tool"
              />
            </div>
          </div>

          <!-- 账户设置 -->
          <div v-if="activeTab === 'settings'">
            <div class="max-w-2xl">
              <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">基本信息</h3>
              <div class="space-y-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    昵称
                  </label>
                  <input
                    v-model="profileForm.nickname"
                    type="text"
                    class="input"
                    placeholder="请输入昵称"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    邮箱
                  </label>
                  <input
                    :value="user?.email || ''"
                    type="email"
                    class="input"
                    disabled
                  />
                  <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">邮箱不可修改</p>
                </div>
                <div class="flex gap-4">
                  <button @click="updateProfile" class="btn btn-primary" :disabled="updating">
                    {{ updating ? '保存中...' : '保存修改' }}
                  </button>
                </div>
              </div>

              <div class="mt-8 pt-8 border-t border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">修改密码</h3>
                <div class="space-y-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      旧密码
                    </label>
                    <input
                      v-model="passwordForm.oldPassword"
                      type="password"
                      class="input"
                      placeholder="请输入旧密码"
                    />
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      新密码
                    </label>
                    <input
                      v-model="passwordForm.newPassword"
                      type="password"
                      class="input"
                      placeholder="请输入新密码"
                    />
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      确认新密码
                    </label>
                    <input
                      v-model="passwordForm.confirmPassword"
                      type="password"
                      class="input"
                      placeholder="请再次输入新密码"
                    />
                  </div>
                  <div class="flex gap-4">
                    <button @click="changePassword" class="btn btn-primary" :disabled="updatingPassword">
                      {{ updatingPassword ? '修改中...' : '修改密码' }}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'

definePageMeta({
  middleware: 'auth'
})

const authStore = useAuthStore()
const $api = useNuxtApp().$api
const toast = useToast()
const router = useRouter()

const user = computed(() => authStore.user)
const activeTab = ref('orders')
const loadingOrders = ref(false)
const loadingFavorites = ref(false)
const updating = ref(false)
const updatingPassword = ref(false)
const uploadingAvatar = ref(false)

const orders = ref<any[]>([])
const favorites = ref<any[]>([])

const profileForm = ref({
  nickname: user.value?.nickname || ''
})

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const avatarInput = ref<HTMLInputElement | null>(null)

const tabs = [
  { id: 'orders', label: '我的订单', icon: 'heroicons:shopping-bag' },
  { id: 'favorites', label: '我的收藏', icon: 'heroicons:heart' },
  { id: 'settings', label: '账户设置', icon: 'heroicons:cog-6-tooth' }
]

const membershipText = computed(() => {
  const type = user.value?.subscriptionType
  if (type === 'premium') return '高级会员'
  if (type === 'basic') return '基础会员'
  return '免费用户'
})

const membershipIcon = computed(() => {
  const type = user.value?.subscriptionType
  if (type === 'premium') return 'heroicons:star-solid'
  if (type === 'basic') return 'heroicons:star'
  return 'heroicons:user'
})

const membershipBadgeClass = computed(() => {
  const type = user.value?.subscriptionType
  if (type === 'premium') return 'bg-gradient-to-r from-yellow-400 to-orange-500 text-white'
  if (type === 'basic') return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
  return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200'
})

// 计算剩余天数
const daysRemaining = computed(() => {
  if (!user.value?.subscriptionEndDate) return 0
  const endDate = new Date(user.value.subscriptionEndDate)
  const today = new Date()
  const diff = endDate.getTime() - today.getTime()
  return Math.max(0, Math.ceil(diff / (1000 * 60 * 60 * 24)))
})

onMounted(async () => {
  await loadOrders()
  profileForm.value.nickname = user.value?.nickname || ''
})

const loadOrders = async () => {
  loadingOrders.value = true
  try {
    orders.value = await $api('/orders') as any[]
  } catch (error) {
    console.error('加载订单失败:', error)
    toast.error('加载订单失败')
  } finally {
    loadingOrders.value = false
  }
}

const loadFavorites = async () => {
  if (favorites.value.length > 0) return // 已加载
  
  loadingFavorites.value = true
  try {
    favorites.value = await $api('/favorites') as any[]
  } catch (error) {
    console.error('加载收藏失败:', error)
    toast.error('加载收藏失败')
  } finally {
    loadingFavorites.value = false
  }
}

// 监听标签切换
watch(activeTab, (newTab) => {
  if (newTab === 'favorites' && favorites.value.length === 0) {
    loadFavorites()
  }
})

const formatDate = (date: string | undefined) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

const getOrderStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待支付',
    paid: '已支付',
    processing: '处理中',
    completed: '已完成',
    refunding: '退款中',
    refunded: '已退款',
    cancelled: '已取消',
    expired: '已过期'
  }
  return statusMap[status] || status
}

const getOrderStatusClass = (status: string) => {
  const classMap: Record<string, string> = {
    pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',
    paid: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
    processing: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200',
    completed: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
    refunding: 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200',
    refunded: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200',
    cancelled: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200',
    expired: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200'
  }
  return classMap[status] || 'bg-gray-100 text-gray-800'
}

const goToPay = (orderId: number) => {
  router.push(`/order/pay/${orderId}?method=wechat_native`)
}

const cancelOrder = async (orderId: number) => {
  if (!confirm('确定要取消这个订单吗？')) return
  
  try {
    await $api(`/orders/${orderId}/cancel`, { method: 'POST' })
    toast.success('订单已取消')
    await loadOrders()
  } catch (error) {
    console.error('取消订单失败:', error)
    toast.error('取消订单失败')
  }
}

// 触发头像上传
const triggerAvatarUpload = () => {
  avatarInput.value?.click()
}

// 处理头像上传
const handleAvatarUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    toast.error('请选择图片文件')
    return
  }
  
  // 验证文件大小（最大2MB）
  if (file.size > 2 * 1024 * 1024) {
    toast.error('图片大小不能超过2MB')
    return
  }
  
  uploadingAvatar.value = true
  try {
    // 创建 FormData
    const formData = new FormData()
    formData.append('file', file)
    
    // 上传文件
    const response = await $api('/upload', {
      method: 'POST',
      body: formData
    }) as { url: string }
    
    // 更新用户头像
    const updatedUser = await $api('/users/profile', {
      method: 'PATCH',
      body: {
        avatar: response.url
      }
    })
    
    authStore.setUser(updatedUser as any)
    toast.success('头像更新成功')
  } catch (error: any) {
    console.error('头像上传失败:', error)
    toast.error(error.data?.message || '头像上传失败')
  } finally {
    uploadingAvatar.value = false
    // 清空文件输入
    if (avatarInput.value) {
      avatarInput.value.value = ''
    }
  }
}

const updateProfile = async () => {
  updating.value = true
  try {
    const updatedUser = await $api('/users/profile', {
      method: 'PATCH',
      body: profileForm.value
    }) as any
    
    // 更新用户信息
    if (user.value) {
      authStore.user = { ...user.value, ...updatedUser }
    }
    toast.success('保存成功')
  } catch (error) {
    console.error('更新失败:', error)
    toast.error('保存失败')
  } finally {
    updating.value = false
  }
}

const changePassword = async () => {
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    toast.error('两次输入的密码不一致')
    return
  }
  
  if (passwordForm.value.newPassword.length < 6) {
    toast.error('密码长度至少为 6 位')
    return
  }
  
  updatingPassword.value = true
  try {
    await $api('/users/change-password', {
      method: 'POST',
      body: {
        oldPassword: passwordForm.value.oldPassword,
        newPassword: passwordForm.value.newPassword
      }
    })
    toast.success('密码修改成功，请重新登录')
    passwordForm.value = { oldPassword: '', newPassword: '', confirmPassword: '' }
    
    // 3秒后跳转到登录页
    setTimeout(() => {
      authStore.logout()
      router.push('/login')
    }, 3000)
  } catch (error: any) {
    console.error('修改密码失败:', error)
    toast.error(error?.data?.message || '修改密码失败')
  } finally {
    updatingPassword.value = false
  }
}

// SEO
useHead({
  title: '个人中心 - DevToolsHub',
  meta: [
    { name: 'robots', content: 'noindex, nofollow' }
  ]
})
</script>

